package com.specialized.orders.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.specialized.orders.common.domain.RealTime;
import com.specialized.orders.service.IRealTimeService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RealTimeOrderConsumer {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private IRealTimeService realTimeService;

    @RabbitListener(queuesToDeclare = @Queue(value = "addorder"))
    public void addOrder(String realTime, Message message, Channel channel){
        RealTime parseObjpect = JSONObject.parseObject(realTime, RealTime.class);
        String messageId = message.getMessageProperties().getMessageId();
        try {
            Long addorder = redisTemplate.opsForSet().add("order", messageId);
            if(addorder>0){
                //下单
                realTimeService.addRealTimeOrdersss(parseObjpect);
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            }
        } catch (IOException e) {
            redisTemplate.delete("order");
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }









}
